package com.miao.im.biz;

import com.miao.im.common.Message;
import com.miao.im.common.annotation.MessageCommand;
import com.miao.im.common.enums.Command;
import com.miao.im.dto.UserRespDto;
import com.miao.im.model.KickOutRequestModel;
import com.miao.im.server.session.SessionContext;
import com.miao.im.server.session.SessionManager;
import com.miao.im.service.auth.IAuthManager;
import com.miao.im.support.handler.AbstractMessageHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

/**
 * @Auther: miaoguoxin
 * @Date: 2021/3/3 16:35
 * @Description:
 */
@Component
@MessageCommand(Command.KICK_OUT)
@Slf4j
public class KickOutRequestHandler extends AbstractMessageHandler<KickOutRequestModel.KickOutRequest> {
    @Autowired
    private IAuthManager<UserRespDto> webAuthManager;

    @Override
    protected void doRead(KickOutRequestModel.KickOutRequest body, Message message) {
        String deviceNumber = body.getTargetDeviceNumber();
        log.info("接收到踢人请求，设备号：{}", deviceNumber);
        SessionManager.sendToDevice(deviceNumber, message,
                future -> SessionManager.getByDeviceNumber(deviceNumber)
                        .ifPresent(sessionContext -> {
                            webAuthManager.logout(sessionContext.getSessionId(), sessionContext.getUserInfo().getDeviceNumber());
                            sessionContext.getChannel().close();
                        }));
    }

    @Override
    protected Mono<Void> doDispatch(KickOutRequestModel.KickOutRequest body, Message message, SessionContext sessionContext) {
        return Mono.empty();
    }

}
